import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {IonSlides, ModalController} from '@ionic/angular';
import {NativeService} from '../../services/native.service';
import {StorageService} from '../../services/storage.service';
import {DomSanitizer} from '@angular/platform-browser';
import {WebView} from '@ionic-native/ionic-webview/ngx';
import {File} from '@ionic-native/file/ngx';
import {FileService} from '../../services/file.service';

declare let Swiper: any;

@Component({
    selector: 'app-preview-picture',
    templateUrl: './preview-picture.component.html',
    styleUrls: ['./preview-picture.component.scss'],
})
export class PreviewPictureComponent implements OnInit {

    constructor(private modalCtrl: ModalController,
                private nativeService: NativeService,
                private ref: ElementRef,
                private storage: StorageService,
                private sanitizer: DomSanitizer,
                private webview: WebView,
                private file: File,
                private fileService: FileService
    ) {
        this.storage.write('preview-picture', 'yes');
    }

    @Input()
    set images(value: Array<string>) {
        this.process(value);
    }

    // tslint:disable-next-line:variable-name
    _images: Array<string>;
    @Input()
    initialIndex: number;
    @ViewChild(IonSlides, {static: true})
    slides: IonSlides;
    touchStart: Touch;
    touchEnd: Touch;
    swiper: any;
    imgs = [];

    ionViewDidEnter() {
        const mySwiper = new Swiper('.swiper-container', {
            loop: false,
            zoom: true,
            runCallbacksOnInit: false,
            initialSlide: this.initialIndex,
            speed: 400,
            spaceBetween: 100

        });
        if (mySwiper) {
            const swiperstyle = this.ref.nativeElement.querySelector('.swiper-container').style;
            swiperstyle.visibility = 'visible';
        }
    }

    ngOnInit() {
    }

    async stopPreview() {
        await this.modalCtrl.dismiss();
    }


    async process(value: Array<string>) {
        const imgPath = this.file.dataDirectory;
        const imgDir = 'bird';
        const tmp = [];
        for (const s of value) {

            try {
                const imgName = s.substr(s.lastIndexOf('/') + 1);
                const filePath = imgPath + imgDir + '/' + imgName;
                const isFileExist = await this.file.checkFile(imgPath, imgDir + '/' + imgName);
                if (isFileExist) {
                    console.log('文件存在' + filePath);
                    this.imgs.push(filePath);
                    tmp.push(this.sanitizer.bypassSecurityTrustUrl(this.webview.convertFileSrc(filePath)));
                } else {
                    tmp.push(s);
                    this.imgs.push(s);
                }
            } catch (e) {
                console.log('图片预览error:' + e);
                tmp.push(s);
                this.imgs.push(s);
            }

        }
        this._images = tmp;
    }

    saveImage() {
        const content = this.ref.nativeElement.querySelectorAll('.swiper-slide');
        let index = 0;
        for (let i = 0; i < content.length; i++) {
            const img = this.ref.nativeElement.querySelector('.swiper-slide-active');
            if (content[i] == img) {
                index = i;
            }
        }
        const url = this.imgs[index];
        this.fileService.saveToPhotoLibrary(url);
    }
}
